package com.inspinia.upms.server.controller.upms;

import com.inspinia.base.cache.CacheUtil;
import com.inspinia.base.common.model.AjaxResult;
import com.inspinia.base.common.model.Status;
import com.inspinia.base.common.model.UserCacheKeys;
import com.inspinia.base.pagination.Pager;
import com.inspinia.base.util.CollectionUtil;
import com.inspinia.base.util.StringUtils;
import com.inspinia.upms.common.model.role.UpmsRole;
import com.inspinia.upms.common.model.role.UpmsRoleVo;
import com.inspinia.upms.rpc.api.UpmsResourceService;
import com.inspinia.upms.rpc.api.UpmsRoleService;
import com.inspinia.upms.server.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.beans.PropertyEditorSupport;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("upms/role/")
public class UpmsRoleController extends BaseController {

    private String prefix = "upms/role/";

    @Resource
    private UpmsRoleService roleService;
    @Resource
    private UpmsResourceService resourceService;

    @InitBinder
    public void intiBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Status.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(Status.valueOf(Integer.valueOf(text)));
            }
        });
    }

    /**
     * 跳转分页分页查询
     *
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String toPaginationPage(Model model) {
        model.addAttribute("roleStatus", Status.values());
        return prefix + "role-pagination";
    }

    /**
     * 查询所有角色
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public List<UpmsRole> list(String dept1,String dept2,String roleName) {
        List<Long> depts =new ArrayList<>();
        if(StringUtils.isNotBlank(dept1) && StringUtils.isNotBlank(dept2)){
            depts.add(Long.valueOf(dept1));
            depts.add(Long.valueOf(dept2));
        }
        List<UpmsRole> roles = roleService.findAll(depts);
        if (StringUtils.isNotBlank(roleName) && CollectionUtil.isNotEmpty(roles)){
            roles = roles.stream().filter(i ->{return i.getRoleName().contains(roleName);}).collect(Collectors.toList());
        }
        return roles;
    }


    /**
     * 创建角色
     *
     * @param role
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "create")
    public AjaxResult create(@Valid UpmsRole role) {
        if (role.getRoleName() != null) {
            UpmsRoleVo vo = new UpmsRoleVo();
            vo.setRoleName(role.getRoleName());
            Pager<UpmsRole> page = roleService.findPage(vo);
            if (page.getList().isEmpty()) {
                roleService.insert(role);
                return new AjaxResult(true);
            } else {
                return new AjaxResult(false, "角色名已存在");
            }

        } else {
            return new AjaxResult(false, "输入名称为空");
        }
    }

    /**
     * 获取角色信息
     *
     * @param id 角色id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public AjaxResult findById(long id) {
        UpmsRole bean = roleService.get(id);
        return new AjaxResult(true, bean);
    }

    /**
     * 编辑角色
     *
     * @param role 角色信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public AjaxResult edit(@Valid UpmsRole role) {
        roleService.update(role);
        return new AjaxResult(true);
    }

    /**
     * 检查角色名是否重复
     *
     * @param name
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "validName", method = RequestMethod.POST)
    public boolean validPhone(String name, Long id) {
        return !roleService.validateName(name, id);
    }

    /**
     * 获取角色已分配的资源
     *
     * @param id 角色id
     * @return
     */
    @ResponseBody
    @RequestMapping("getResources")
    public List<Long> getResources(Long id) {
        return roleService.getResources(id);
    }

    /**
     * 删除角色
     *
     * @param id 角色id
     * @return
     */
    @ResponseBody
    @RequestMapping("delRole")
    public AjaxResult del(Long id) {
        int n = roleService.delete(id);
        if (n > 0){
            return new AjaxResult(true,"操作成功");
        }else {
            return new AjaxResult(false,"操作失败");
        }
    }

    /**
     * 给角色分配资源
     *
     * @param resourceIds 资源id集合
     * @param roleId      角色id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "setResources", method = RequestMethod.POST)
    public AjaxResult setResources(@RequestParam(name = "resourceIds[]", required = false, defaultValue = "") Long[] resourceIds, Long roleId) {

        //用户set集合来排除资源ID中的重复元素
        Set<Long> distResourceIds = new HashSet<>(Arrays.asList(resourceIds));
        //系统 默认将定级菜单选中
        distResourceIds.add(1L);

        //获得全部菜单 --将菜单的父级菜单也默认选中
        distResourceIds = resourceService.getDistResources(distResourceIds);

        resourceIds = new Long[distResourceIds.size()];
        distResourceIds.toArray(resourceIds);

        roleService.setResources(resourceIds, roleId);


        CacheUtil.deleteByReg(UserCacheKeys.getUserMenuKey(getPrincipalId()));
        return new AjaxResult(true);
    }
}